/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2015年3月18日         luwei
 */

package com.coocaa.app.gamecenter.pages.home;

import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

import com.alibaba.fastjson.JSONObject;
import com.coocaa.app.gamecenter.framework.GameCenterActivity;
import com.coocaa.app.gamecenter.pages.home.data.CategoryDataCahce;
import com.coocaa.app.gamecenter.pages.home.data.RecommendDataCache;
import com.coocaa.framework.system.JoyStickManager;
import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LiteURI;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litecache.data.client.LiteImageCache;
import com.coocaa.x.service.litecache.data.client.LiteImageCache.LiteImageCacheLoadListener;
import com.coocaa.x.service.litecache.data.client.LiteImageCache.LiteImageCacheObject;
import com.coocaa.x.service.litecontent.LiteContentServiceConnecter;
import com.coocaa.x.service.litecontent.data.store.com_coocaa_theme.RP_Boolean;
import com.coocaa.x.service.litedb.data.client.LiteDBSupport;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppAdInfo;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreBean;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.skyworth.webSDK.webservice.tcappstore.GameIndex;
import com.skyworth.webSDK.webservice.tcappstore.GameIndexData;
import com.tianci.appstore.R;
import com.tianci.appstore.ui.data.SkyCategoryData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.widget.CatchImageView;
import com.tianci.appstore.ui.widget.SkyCustomLayout.BlockData;
import com.tianci.appstore.utils.SkyConstants;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GameMainActivity extends GameCenterActivity implements LiteImageCacheLoadListener {
    private GameCenterController mGameCenterController = null;
    private LiteImageCacheObject mAdPic = null;
    private ImageView mSplashAd = null;
    private String mSplashUrl = "";
    private static final String SPLASH_PIC = "game_center_splash_ad_url";
    private boolean mIsDefault = true;
    private boolean mIsLoadData = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        enableTitleView(false);
        //move to themeactivity
//        Fresco.initialize(CoocaaApplication.getContext());
        super.onCreate(savedInstanceState);
        LogUtils.SubmitLog log = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE,"gc2_launch_with_joystick");
        List<JoyStickManager.JoyStickDevice> list = JoyStickManager.getDeviceList();
        LogUtils.d("log","oncreate  (list != null && list.size() > 0):"+(list != null && list.size() > 0));
        if(list != null && list.size() > 0)
            log.addParam("device_type","JOYSTICK");
            else
            log.addParam("device_type","NONE");
        LogUtils.submit(log);

    }

    @Override
    protected Map<String, String> getPageStartParams() {
        HashMap<String,String> map = new HashMap<String,String>();
        String channel = LiteAppApplication.getContentChannel();
        map.put("channel",channel);
        return map;
    }

    @Override
    protected View createContentView() {
        if(mGameCenterController == null)
            mGameCenterController = new GameCenterController(GameMainActivity.this);
        final GameCenterLayout layout = mGameCenterController.getLayout();
        mSplashAd = new CatchImageView(this);
        mSplashAd.setBackgroundResource(R.drawable.ui_sdk_app_bg);
        post(new Runnable() {

            @Override
            public void run() {
                if (!LiteAppApplication.getFirstLaunch("FIRST_KYB_OPEN")) {
                    try {
                        XServiceManager.getLiteCCConnectorService().firstStartAppPoints("FIRST_KYB_OPEN");
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
                try {
                    mSplashUrl = XServiceManager.getLiteConfigService().getStringValue(SPLASH_PIC, "");
                } catch (RemoteException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

                boolean hasArsenal = false;
                LiteURI uri = LiteURI.create("store://com.coocaa.arsenal/openArsenal");
                try {
                    String result = LiteContentServiceConnecter.getService().call(uri.toString());

                    LogUtils.i("xfk", "result: "+result);
                    RP_Boolean rpBoolean = JSONObject.parseObject(result, RP_Boolean.class);
                    if(rpBoolean != null) {
                        hasArsenal = rpBoolean.resource;
                    }

                    LogUtils.i("1111", "2 hasArsenal: "+hasArsenal);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                if (!mSplashUrl.equals("")) {
                    mIsDefault = false;
                    LiteImageCache.getInstance().load(mSplashUrl, GameMainActivity.this,
                            SkyConstants.Div(1280), SkyConstants.Div(720));
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mSplashAd != null){
                                mSplashAd.setScaleType(ScaleType.CENTER);
                                mSplashAd.setImageResource(R.drawable.game_center_default_splash);
                            }
                        }
                    });
                }
                if (mIsDefault) {
                    int num = 0;
                    while (true) {
                        num++;
                        if ((mIsLoadData && num > 100) || num >= 150) {
                            final boolean finalHasArsenal1 = hasArsenal;
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mMainlayout.removeView(mSplashAd);
                                    mMainlayout.removeView(layout);
                                    mMainlayout.addView(layout);
                                    layout.initFocus();
                                    if(finalHasArsenal1)
                                        layout.showArsenal();
                                    recycleAd();
                                    if (!mIsLoadData) {
                                        showloading();
                                    }
                                }
                            });
                            break;
                        } else {
                            try {
                                Thread.sleep(20);
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    final boolean finalHasArsenal = hasArsenal;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mMainlayout.removeView(mSplashAd);
                            mMainlayout.removeView(layout);
                            mMainlayout.addView(layout);
                            layout.initFocus();
                            if(finalHasArsenal)
                                layout.showArsenal();
                            if (mAdPic != null) {
                                recycleAd();
                                mAdPic.recyle();
                            }
                            if (!mIsLoadData) {
                                showloading();
                            }
                        }
                    });
                }
            }
        });
        postDelayed(new Runnable() {
            @Override
            public void run() {
                loadData("");
            }
        }, 1500);
        return mSplashAd;
    }

    public void recycleAd() {
        if (mSplashAd != null){
            Drawable drawable = mSplashAd.getBackground();
            if (drawable != null) {
                drawable.setCallback(null);
            }
            mSplashAd.setImageBitmap(null);
            mSplashAd.setBackgroundDrawable(null);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    protected void onDestroy() {
        mGameCenterController.destory();
        mLoading = null;
        super.onDestroy();

        //move to themeactivity
        // Fresco.shutDown();
    }

    @Override
    protected void loadData() throws Exception {

    }

    private void loadData(String text) {
        try {
            final ArrayList<SkyListAppData> baseDatas = new ArrayList<SkyListAppData>();
            startSlowNetTimerDalay(7000);
            boolean cacheRecommend = false;
            boolean cacheCategory = false;
            while (true) {
                try {
                    cacheRecommend = refreshRecommendCache();
                    if (!cacheRecommend) {
                        if (!checkNet()) {
                            showDefaultData(getString(R.string.connection_more_wonderful));
                            cancelSlowNetTimer();
                            mIsLoadData = true;
                            return;
                        }
                    }
                    cacheCategory = refreshCategoryCache();
                    if (cacheRecommend && cacheCategory) {
                        mIsLoadData = true;
                        hideloading();
                    }
                    break;
                } catch (Exception e) {
                    LogUtils.i("luwei", e.getMessage());
                    Thread.sleep(50);
                }
            }
            LogUtils.i("luwei", "recommend use cache is " + cacheRecommend);
            LogUtils.i("luwei", "category use cache is " + cacheCategory);
            GameIndex gameIndex = CoocaaApplication.getCoocaaWebService().getAppStoreService()
                    .getGameIndex("ZoneData");
            cancelSlowNetTimer();
            if (gameIndex != null && gameIndex.recommend_games != null
                    && gameIndex.recommend_games.size() > 0) {
                if (!cacheRecommend) {
                    refreshRecommend(baseDatas, gameIndex);
                }
                if (gameIndex.game_class != null && gameIndex.game_class.size() > 0) {
                    if (!cacheCategory) {
                        refreshCategory(gameIndex);
                    }
                    cacheCategory(gameIndex);
                }
                cacheRecommend(gameIndex.recommend_games);
            } else {
                if (!cacheRecommend) {
                    showDefaultData(getString(R.string.no_app_list));
                }
            }
            mIsLoadData = true;
            hideloading();
            getAdInfo();
        } catch (AppStoreException e) {
            LogAPIForAppStore.reportInterfaceError("游戏中心首页数据", Android.throwable2String(e));
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getAdInfo() {
        try {
            final AppAdInfo info = CoocaaApplication.getCoocaaWebService().getAppStoreService()
                    .getIndexAd();
            if (info != null && info.picUrl != null && !info.picUrl.equals("")) {
                if (!info.picUrl.equals(mSplashUrl)) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            LiteImageCache.getInstance().load(info.picUrl, GameMainActivity.this,
                                    SkyConstants.Div(1280), SkyConstants.Div(720));
                        }
                    }).start();
                }
            } else {
                XServiceManager.getLiteConfigService().saveStringConfig(SPLASH_PIC, "");
            }
        } catch (AppStoreException e) {
            LogAPIForAppStore.reportInterfaceError("获取游戏首页闪屏广告", Android.throwable2String(e));
            e.printStackTrace();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void refreshCategory(GameIndex gameIndex) {
        final CategoryData data = new CategoryData();
        data.mColumn = gameIndex.column;
        data.mRow = gameIndex.row;
        data.mWidth = 350;
        data.mHeight = 246;
        List<BlockData> blockDatas = new ArrayList<BlockData>();
        data.mLayoutData = blockDatas;
        List<SkyCategoryData> categoryDatas = new ArrayList<SkyCategoryData>();
        data.mCategoryDatas = categoryDatas;
        for (GameIndexData indexData : gameIndex.game_class) {
            GameCategoryData skyCategoryData = new GameCategoryData(indexData.classId,
                    indexData.title);
            skyCategoryData.imgurl = indexData.icon;
            skyCategoryData.uri = indexData.uri;
            categoryDatas.add(skyCategoryData);
            BlockData blockData = getBlockData(indexData.shape, data.mColumn, data.mRow);
            if (blockData != null) {
                blockDatas.add(blockData);
            }
        }
        refreshCategoryUI(data);
    }

    public void refreshCategoryUI(final CategoryData data) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mGameCenterController.addCategoryLayout(data);
                mGameCenterController.getLayout().showDownArrow();
            }
        });
    }

    private BlockData getBlockData(String shape, int col, int row) {
        BlockData blockData = new BlockData();
        if (shape == null || shape.equals("")) {
            return null;
        }
        int[] block = ReadXMLParser.generatePos(shape);
        blockData.mBlock = block;
        int len = block.length;
        blockData.mColNum = 1;
        blockData.mRowNum = 1;
        if (len > 1) {
            if (len % 2 != 0) {
                blockData.mColNum = len;
            } else {
                boolean column = true;
                for (int i = 1; i < len; i++) {
                    if (block[i] - block[i - 1] < col - 1 && column) {
                        blockData.mColNum++;
                    } else if (block[i] - block[i - 1] >= col - 1) {
                        blockData.mRowNum++;
                        column = false;
                    }
                }
            }
        }
        if (block[0] < col) {
            blockData.mTurnPage = new boolean[]{false, true, false, false};
        } else if (block[0] > col * (row - 1)) {
            blockData.mTurnPage = new boolean[]{false, false, false, true};
        } else {
            blockData.mTurnPage = new boolean[]{false, false, false, false};
        }
        return blockData;
    }

    private boolean refreshRecommendCache() throws Exception {
        RecommendDataCache cache = new RecommendDataCache();
        List<LiteDBSupport> caches = cache.selectAll();
        if (caches != null && caches.size() > 0) {
            ArrayList<SkyListAppData> appDatas = new ArrayList<SkyListAppData>();
            for (LiteDBSupport support : caches) {
                cache = (RecommendDataCache) support;
                SkyListAppData appData = new SkyListAppData(cache.id, cache.name, cache.img, "",
                        cache.pname);
                appData.setUri(cache.uri);
                List<String> control = new ArrayList<String>();
                control.add(cache.control);
                appData.setControll(control);
                appDatas.add(appData);
            }
            refreshRecommendUI(appDatas);
            return true;
        }
        return false;
    }

    private boolean refreshCategoryCache() throws Exception {
        CategoryDataCahce cache = new CategoryDataCahce();
        List<LiteDBSupport> caches = cache.selectAll();
        if (caches != null && caches.size() > 0) {
            CategoryData data = new CategoryData();
            data.mWidth = 350;
            data.mHeight = 246;
            List<BlockData> blockDatas = new ArrayList<BlockData>();
            List<SkyCategoryData> categoryDatas = new ArrayList<SkyCategoryData>();
            data.mLayoutData = blockDatas;
            data.mCategoryDatas = categoryDatas;
            for (LiteDBSupport support : caches) {
                cache = (CategoryDataCahce) support;
                data.mColumn = cache.column;
                data.mRow = cache.row;
                BlockData blockData = getBlockData(cache.shape, cache.column, cache.row);
                if (blockData != null) {
                    blockDatas.add(blockData);
                }
                GameCategoryData categoryData = new GameCategoryData(cache.id, cache.name);
                categoryData.imgurl = cache.img;
                categoryData.uri = cache.uri;
                categoryDatas.add(categoryData);
            }
            refreshCategoryUI(data);
            return true;
        }
        return false;
    }

    public void cacheRecommend(List<AppStoreBean> baseDatas) throws Exception {
        synchronized (GameMainActivity.this) {
            RecommendDataCache recommendCache = new RecommendDataCache();
            recommendCache.deleteAll();

            for (AppStoreBean appData : baseDatas) {
                recommendCache.setData(appData.id, appData.name, appData.lmg, appData.packagename,
                        appData.extra.get(0),appData.uri);
                recommendCache.insert();
            }
        }
    }

    public void cacheCategory(GameIndex gameIndex) throws Exception {
        synchronized (GameMainActivity.this) {
            CategoryDataCahce categoryCache = new CategoryDataCahce();
            categoryCache.deleteAll();
            for (GameIndexData indexData : gameIndex.game_class) {
                categoryCache.setData(indexData.classId, gameIndex.column, gameIndex.row,
                        indexData.icon, indexData.shape, indexData.title, indexData.uri);
                categoryCache.insert();
            }
        }
    }

    public void refreshRecommend(final ArrayList<SkyListAppData> baseDatas, GameIndex gameIndex) {
        baseDatas.clear();
        for (AppStoreBean bean : gameIndex.recommend_games) {
            SkyListAppData data = new SkyListAppData(bean.id, bean.name, bean.lmg, "",
                    bean.packagename);
            data.setUri(bean.uri);
            data.setControll(bean.extra);
            for (int i = 0; i < bean.extra.size(); i++) {
                LogUtils.d("luwei", "control " + bean.extra.get(i));
            }
            baseDatas.add(data);
        }
        refreshRecommendUI(baseDatas);
    }

    public void refreshRecommendUI(final ArrayList<SkyListAppData> baseDatas) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mGameCenterController.refreshRecommand(baseDatas);
            }
        });
    }

    public void showDefaultData(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mGameCenterController.hideFocusView();
                mGameCenterController.setMyGameFocus();
                hideloading();
                setLoadDataErrorMsg(msg);
            }
        });
    }

    @Override
    protected void updateContentView() {

    }

    @Override
    public void onImageLoaded(LiteImageCacheObject obj) {
        try {
            if (obj != null && obj.getBitmap() != null) {
                mAdPic = obj;
                if (mAdPic.getUrl().equals(mSplashUrl)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mSplashAd.setBackgroundDrawable(new BitmapDrawable(mAdPic.getBitmap()));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else {
                    XServiceManager.getLiteConfigService().saveStringConfig(SPLASH_PIC,
                            mAdPic.getUrl());
                    if (mAdPic.getBitmap() != null) {
                        mAdPic.recyle();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getName() {
        return "酷游吧主页";
    }
}
